<?php
declare (strict_types = 1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminModel;
use App\Models\SystemConfigModel;
use App\Models\SystemMenusModel;
use App\Services\Admin\LoginService;
use Illuminate\Support\Facades\View;

class BaseController extends Controller
{
    /**
     * 当前登陆管理员信息
     * @var
     */
    protected static $adminInfo;

    /**
     * 当前登陆管理员ID
     * @var
     */
    protected static $adminId;

    /**
     * 当前管理员权限
     * @var array
     */
    protected $auth = [];

    /**
     * 每页数量
     * @var [type]
     */
    protected $pageSize = 20;

    public function __construct()
    {
        error_reporting(E_ALL ^ E_NOTICE);
        View::share(['pageSize'=>$this->pageSize]);
        $loginCheck = LoginService::loginCheck();
        if($loginCheck == false) {
            session()->flush();
            $url = url("admin/login");
            //重定向跳转
            redirect($url)->send();
        }
        self::$adminInfo = session("adminInfo");
        self::$adminId = session("adminId");

        self::$adminInfo['admin_time'] = date('Y-m-d H:i:s',time());
        View::share(['admin'=>self::$adminInfo,'siteConfig'=>SystemConfigModel::getConfig()]);

        $this->jurisdiction();
    }

    /**
     * 验证权限
     * @param string $value [description]
     */
    private function jurisdiction()
    {
        $roles = AdminModel::getJurisdiction(session("adminId"));
        if(empty($roles)) exit('系统繁忙，请重试');
        $field = ['id','icon','menu_name','controller','action','params'];

        if(strtolower($roles['rules']) != 'all'){
            $rules = explode(',',$roles['rules']);
            //菜单
            $menu = SystemMenusModel::whereIn('id',$rules)->where(["pid"=>0,"is_show"=>1])->orderBy("sort","asc")->select($field)->get()->toArray();
            if($menu){
                foreach ($menu as $k => $v) {
                    $menu[$k]['icon'] = SystemMenusModel::getIcon($v['icon']);
                    $sub = SystemMenusModel::whereIn('id',$rules)->where(["pid"=>$v['id'],"is_show"=>1])->orderBy("sort","asc")->select($field)->get()->toArray();
                    $menu[$k]['sub'] = $sub;
                    if($sub) {
                        foreach ($sub as $k1 => $v1) {
                            $menu[$k]['sub'][$k1]['icon'] = SystemMenusModel::getIcon($v1['icon']);
                            $menu[$k]['sub'][$k1]['sub'] = SystemMenusModel::whereIn('id',$rules)->where(["pid"=>$v1['id'],"is_show"=>1])->orderBy("sort","asc")->select($field)->get()->toArray();
                        }
                    }
                }
            }
        }else{
            //菜单
            $menu = SystemMenusModel::where(["pid"=>0,"is_show"=>1])->orderBy("sort","asc")->select($field)->get()->toArray();
            if($menu){
                foreach ($menu as $k => $v) {
                    $menu[$k]['icon'] = SystemMenusModel::getIcon($v['icon']);
                    $sub = SystemMenusModel::where(["pid"=>$v['id'],"is_show"=>1])->orderBy("sort","asc")->select($field)->get()->toArray();
                    $menu[$k]['sub'] = $sub;
                    if($sub) {
                        foreach ($sub as $k1 => $v1) {
                            $menu[$k]['sub'][$k1]['icon'] = SystemMenusModel::getIcon($v1['icon']);
                            $menu[$k]['sub'][$k1]['sub'] = SystemMenusModel::where(["pid"=>$v1['id'],"is_show"=>1])->orderBy("sort","asc")->select($field)->get()->toArray();
                        }
                    }
                }
            }
        }

        View::share("menu",$menu);

        //防止输入URL，跳过验证权限
        $check_url = [
            '/admin/index', //主页
            '/admin/welcome',  //主页
            '/admin/index/currEdit',  //通用修改
            '/admin/article.article/cate', //文章绑定分类
        ];

        if(strtolower($roles['rules']) != 'all'){
            $all_menu = SystemMenusModel::whereIn('id',$rules)->select(["id","pid","icon","menu_name","controller","action","params"])->get()->toArray();
            $request_url = request()->getPathInfo();
            if($all_menu) {
                foreach ($all_menu as $k => $v) {
                    if($v['controller'] && $v['action'] && $v['pid'] != 0) {
                        $url = "/admin/{$v['controller']}/{$v['action']}";
                        array_push($check_url, $url);
                    }
                }
            }
            if(!in_array($request_url, $check_url) && !strpos(request()->getRequestUri(), 'page')){
                if(request()->ajax()){
                    header('Content-Type:application/json; charset=utf-8');
                    exit(json_encode(['code'=>500, 'msg'=>'抱歉，您暂无访问权限']));
                }
                exit('抱歉，您暂无访问权限');
            }
        }
    }

    /**
     * 渲染layui.table
     * @param array $list 查询后的分页数组
    */
    public function rjson($list = [])
    {
        $arr['code'] = 0;
        $arr['msg'] = "OK";
        $arr['count'] = $list['total'] ? : 0;
        $arr['data'] = $list['data'] ? : [];
        return json_encode($arr);
    }
}
